package com.sutdyyang.springbootmq.consumer;

import com.rabbitmq.client.Channel;
import com.studyyang.springbootmq.entity.Employee;
import com.sutdyyang.springbootmq.entity.constant.RabbitMqConsumerConstant;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.io.IOException;
import java.util.Map;

/**
 * @Author yangjin
 * @Description
 * @Date 2021/11/3/13:51
 **/
@Component
public class MessageConsumer {
    /**
     * 处理消息
     * @RabbitHandler 告诉springboot该方法进行接受消息并处理，该方法运行后会处于等待状态，有新的消息就会自动触发方法逻辑进行消息处理
     * @RabbitListener 声明式定义接收消息的交换机以及队列所绑定的信息
     * @payload 将接受的消息进行反序列化处理
     * @Header 接收消息中的附加信息
     */
    @RabbitHandler
    @RabbitListener(
            bindings = @QueueBinding(
                    value = @Queue(value = RabbitMqConsumerConstant.QUEUE_MESSAGE_SENDER,durable = "true"),
                    exchange = @Exchange(value = RabbitMqConsumerConstant.EXCHANGE_MESSAGE_SENDER, type = "topic"),
                    key = "#"
            )
    )
    public void handlerMessage(@Payload Employee employee,
                               Channel channel,
                               @Headers Map<String,Object> headers) throws IOException {
        System.out.println("======================开始处理消息=========================");
        //处理消息，进行输出
        System.out.println("接收到的消息信息：" + employee);
        //接收处理后消息都要进行消息确认
        if (!ObjectUtils.isEmpty(headers)) {
            Long tagId = (Long) headers.get(AmqpHeaders.DELIVERY_TAG);
            channel.basicAck(tagId, false);
        }
        System.out.println("======================消息处理完毕=========================");
    }

}
